import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getName } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

const connetSse = () => {
  // 使用sse 与server 建立连接
  const source = new EventSource(
    process.env.VUE_APP_BASE_API + '/sse/beginconnect/' + getName()
  )
  source.addEventListener(
    'open',
    function() {
      console.log('建立连接')
    },
    false
  )
  source.addEventListener(
    'message',
    function(e) {
      console.log(e)
      const token = e || getToken()
      console.log(token)
      store.dispatch('user/reflashToken', token).then(() => { // 刷新token的值
        console.log('token已经刷新')
        location.reload() // 刷新页面
      })
    },
    false
  )
  source.addEventListener(
    'error',
    e => {
      if (e.readyState === EventSource.CLOSED) {
        console.log('sse error')
      }
    },
    false
  )
}

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent -- 在请求发起之前执行的代码
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['token'] = getToken()
      config.headers['token'] = store.getters.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom respCode
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // if the custom respCode is not 200, it is judged as an error.
    // 响应code不为200则判断为响应出错
    const res = response.data.respOutMsgHeader
    const { msg } = res
    if (res.respCode !== 200) {
      Message({
        message: msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      // 600: Illegal token 非法token ; 50012: Other clients logged in 其他客户端已登录（单态的时候-暂未设计）; 602: Token expired token过期;
      if (res.respCode === 600 || res.respCode === 50012 || res.respCode === 602) { //  res.respCode === 602 超过有效延长校验时间 token过期需要重新登陆
        // to re-login 重新登陆
        MessageBox.confirm('由于超过一定时长未进行请求操作，服务器判断你已经离开并将你登出, 你可以选择取消并留在当前网页, 或者再次登陆', '确认登出？', {
          confirmButtonText: '重登',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { // 请求报错
          console.log('请求出错')
          store.dispatch('user/resetToken').then(() => { // 重置token的值
            location.reload() // 刷新页面
            connetSse.close()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      console.log('响应成功 200')
      return response
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export function SSE() {
  return connetSse()
}
export default service
